//
//  FindViewController.m
//  FoodList
//
//  Created by 王金晶 on 16/4/6.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "FindViewController.h"
#import "RequestManger.h"
#import "FindModel.h"
#import "PictureView.h"
#import "FindTableViewCell.h"
#import "FindSecondViewController.h"
#import <UIImageView+WebCache.h>
#import "CookingStyleViewController.h"
#import "FoodMateriaViewController.h"
#import <MJRefresh.h>
@interface FindViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *modelArray;
@property(nonatomic,strong)NSMutableArray *imageArray;
@property(nonatomic,strong)PictureView *pictureView;
@property(nonatomic,assign)NSInteger index;
@end

@implementation FindViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.alpha = 1;
    _pictureView.scrollerView.contentOffset = CGPointMake(0, 0);
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)dealloc
{   //关闭定时器
    [_pictureView.timer setFireDate:[NSDate distantFuture]];
    _pictureView.timer = nil;
}
- (void)getData
{   if(_imageArray == nil)
  {
      _imageArray = [NSMutableArray array];
  }
    [RequestManger requestWithURL:@"http://www.xdmeishi.com/index.php?m=mobile&c=index&a=getHomeEntity" requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //获取轮播图图片
        [_imageArray removeAllObjects];
        NSArray *dataArray = dic[@"data"][@"adverts"];
        for (NSDictionary *dic in dataArray) {
            NSString *string = dic[@"imageUrl"];
            [_imageArray addObject:string];
        }
        [_imageArray removeObjectAtIndex:0];
        [_imageArray removeObjectAtIndex:0];
        dispatch_async(dispatch_get_main_queue(), ^{
        self.pictureView = [[PictureView alloc]initWithFrame:CGRectMake(0, 0, Width, 200) imageArray:_imageArray];
            [self.view addSubview:self.pictureView];

        });
        
    } error:nil];
}
- (void)getModelArray:(NSInteger)number
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    [RequestManger requestWithURL:[NSString stringWithFormat:@"http://www.xdmeishi.com/index.php?m=mobile&c=index&a=getRecipeTheme&id=16&pageNum=%ld&pageSize=20",number] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        [_modelArray removeAllObjects];
        NSArray *array = dic[@"data"];
        for (NSDictionary *dic in array) {
            FindModel *model = [[FindModel alloc]init];
            if (![dic[@"ingredients"] isKindOfClass:[NSNull class]]) {
                [model setValue:dic[@"ingredients"] forKey:@"myingredients"];
            }
            NSDictionary *referrerDic = dic[@"referrer"];
            [model setValuesForKeysWithDictionary:referrerDic];
            [model setValuesForKeysWithDictionary:dic];
            [_modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    } error:nil];
}
#pragma mark ---------下拉刷新 上拉加载-----------------
- (void)mjRefresh:(UITableView *)tableView
{
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _index = 1;
        [self getModelArray:1];
        [tableView.mj_header endRefreshing];
    }];
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self getModelArray: _index + 1];
        [tableView.mj_footer endRefreshing];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"发现";
    
    [self getData];
    [self getModelArray:1];
    //开启定时器
    [_pictureView.timer setFireDate:[NSDate distantPast]];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 1000;
    
    [self mjRefresh:_tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"find"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"FindTableViewCell" owner:nil options:nil].firstObject;
    }
    cell.model = _modelArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell
    ;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FindSecondViewController *findSecondView = [[FindSecondViewController alloc]initWithNibName:@"FindSecondViewController" bundle:nil];
    FindModel *model = _modelArray[indexPath.row];
    findSecondView.myID = model.myID;
    findSecondView.name = model.name;
    findSecondView.imageURL = model.imageUrl;
    [self.navigationController pushViewController:findSecondView animated:YES];
}
#pragma mark ------- 跳转到菜谱界面 ----------
- (IBAction)cook:(id)sender {
    // 跳转时隐藏barButton
    self.hidesBottomBarWhenPushed = YES;
    CookingStyleViewController *cook = [[CookingStyleViewController alloc]initWithNibName:@"CookingStyleViewController" bundle:nil];
    [self.navigationController pushViewController:cook animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
#pragma Mark ----- 跳转食材界面 ---------
- (IBAction)food:(id)sender {
    self.hidesBottomBarWhenPushed = YES;
    FoodMateriaViewController *food = [[FoodMateriaViewController alloc]initWithNibName:@"FoodMateriaViewController" bundle:nil];
    [self.navigationController pushViewController:food animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
